package com.etime.shycourse.controller.wx.rss;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信订阅消息服务层
 */
@Service
public class WXRSSService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${appid}")
    private String appid;
    @Value("${secret}")
    private String secret;

    /**
     * 发送微信推送消息
     *
     * @param wxrssData 推送消息数据
     * @return
     */
    public String pushmessage(WXRSSData wxrssData) {
        RestTemplate restTemplate = new RestTemplate ();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + getAccessToken ();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity (url, wxrssData, String.class);
        return responseEntity.getBody ();
    }

    /**
     * 获取access_token
     * 1、首先判断redis缓存中是否有access_token
     * 2、如果有，直接从缓存中获取access_token；
     * 3、如果没有，获取access_token，然后保存到缓存中，并返回
     *
     * @return
     */
    public String getAccessToken() {
        String access_token = "";
        if (stringRedisTemplate.hasKey ("access_token")) {
            access_token = stringRedisTemplate.boundValueOps ("access_token").get ();
        } else {
            Map<String, String> token = getAccessTokenFormWX ();
            stringRedisTemplate.boundValueOps ("access_token").set (token.get ("access_token"));
            int expire_in = Integer.parseInt (token.get ("expires_in"));
            stringRedisTemplate.boundValueOps ("access_token").expire (expire_in - 120, TimeUnit.SECONDS);
            access_token = token.get ("access_token");
        }
        return access_token;
    }

    /**
     * 从微信服务器端获取access_token
     *
     * @return
     */
    private Map<String, String> getAccessTokenFormWX() {
        RestTemplate restTemplate = new RestTemplate ();
        Map<String, String> map = new HashMap<> ();
        map.put ("APPID", appid);
        map.put ("APPSECRET", secret);
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
        ResponseEntity<String> responseEntity = restTemplate.getForEntity (url, String.class, map);
        String body = responseEntity.getBody ();
        JSONObject object = JSON.parseObject (body);
        String access_token = object.getString ("access_token");
        String expires_in = object.getString ("expires_in");
        Map<String, String> rtn = new HashMap<> ();
        rtn.put ("access_token", access_token);
        rtn.put ("expires_in", expires_in);
        return rtn;
    }
}
